#pragma once
#include <memory>
#include <sys/epoll.h>

#include "InetAddr.hpp"
#include "log.hpp"
#include "Socket.hpp"

using namespace socket_ns;

class EpollServer
{
    const static int gnum = 64;
    const static int defaultfd = -1;

public:
    EpollServer(uint16_t port)
        : _port(port), _listensock(std::make_unique<Tcpsocket>()), _epfd(defaultfd)
    {
        InetAddr addr("0", _port);
        _listensock->BuildListenSocket(addr);
        _epfd = ::epoll_create(128);
        if (_epfd < 0)
        {
            LOG(FATAL, "epoll_create error\n");
            exit(5);
        }
        LOG(DEBUG, "epoll_create success, epfd: %d\n", _epfd);
        // 3. 只有一个listensock, listen sock 关心的事件：读事件
        struct epoll_event ev;
        ev.events = EPOLLIN;
        ev.data.fd = _listensock->SockFd(); //???
        epoll_ctl(_epfd, EPOLL_CTL_ADD, _listensock->SockFd(), &ev);
    }
    ~EpollServer()
    {
        _listensock->Close();
        if(_epfd>=0)
        {
            ::close(_epfd);
        }
    }
    


private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensock;
    int _epfd;

    struct epoll_event _recv[gnum];
};